package com.heyidlebooks.utils;

import java.io.File;
import java.io.IOException;
import java.text.ParseException;
import java.util.Date;

import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.analysis.cjk.CJKAnalyzer;
import org.apache.lucene.analysis.standard.StandardAnalyzer;
import org.apache.lucene.document.Document;
import org.apache.lucene.queryParser.QueryParser;
import org.apache.lucene.search.Hits;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.search.Query;
import org.apache.lucene.search.Searcher;
import org.apache.lucene.search.TopDocs;
import org.apache.lucene.store.Directory;
import org.apache.lucene.store.FSDirectory;

public class IndexSearch {

	/**
	 * @param args
	 */
	public static void main(String[] args) throws Exception {
		search(new File("c:\\indexes"), "教程");

	}

	/**
	 * Search Function
	 * 
	 * @since $Release$
	 */
	public static void search(File indexDir, String q) throws Exception
    {

        Directory fsDir = FSDirectory.getDirectory(indexDir, false);
        IndexSearcher is = new IndexSearcher(fsDir);

        QueryParser qp = new QueryParser("name", new CJKAnalyzer());
        Query query = qp.parse(q);

        long start = new Date().getTime();
        Hits hits = is.search(query);
        long end = new Date().getTime();
//        System.err.println(
//            "Found " + hits.length() + " document(s) (in " + (end – start) +
//            " milliseconds) that matched query '" + q + "':"
//            );

        for (int i = 0; i < hits.length(); i++)
        {

            Document doc = hits.doc(i);
            System.out.println(doc.get("name"));
        }
    }
}
